package org.example.ai_chat.service.impl;

import org.example.ai_chat.mapper.AiMemoryMapper;
import org.example.ai_chat.mapper.AiSessionMapper;
import org.example.ai_chat.mapper.UserMapper;
import org.example.ai_chat.mapper.userStatusMapper;
import org.example.ai_chat.pojo.ai_memory;
import org.example.ai_chat.pojo.ai_session;
import org.example.ai_chat.pojo.user_status;
import org.example.ai_chat.pojo.users;
import org.example.ai_chat.service.UserService;
import org.example.ai_chat.util.pwd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private userStatusMapper userStatusMapper;
    @Autowired
    private AiMemoryMapper aiMemoryMapper;
    @Autowired
    private AiSessionMapper aiSessionMapper;

    @Override
    public List<users> getAllUser() {

        return userMapper.getAllUsers();
    }

    @Override
    public users getUserById(int id) {
        return userMapper.getUserById(id);
    }

    @Override
    public users getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public Integer addUser(users user) {
         userMapper.addUser(user);
         user_status userStatus = new user_status();
         userStatus.setUser_id(user.getUser_id());
         userStatus.setOnline_status("offline");
         return userStatusMapper.insertUserStatus(userStatus);

    }

    @Override
    public boolean login(int id,String password_hash) {
        String password = pwd.getSHA256Hash(password_hash);

        if (password.equals(userMapper.getUserById(id).getPassword_hash())) {
            userStatusMapper.updateUserStatus(id,"online");
            return true;
        }
        return false;
    }

    @Override
    public List<List<ai_memory>> getUserMemoryById(int id) {
        List<ai_session> sessions=aiSessionMapper.getSessionByUserId(id);
        List<List<ai_memory>> memoryList=new ArrayList<>();
        for (ai_session session:sessions) {
            memoryList.add(aiMemoryMapper.selectByConversationId(Integer.toString(session.getId())));
        }

        return memoryList;
    }

    @Override
    public int setSession(ai_session session) {
        aiSessionMapper.insertSession(session);
        return  session.getId();
    }

}
